package cn.edu.sysu.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.edu.sysu.dto.ProblemDto;
import cn.edu.sysu.dto.UserDto;
import cn.edu.sysu.util.Transaction;


public enum ProblemDao {

	INSTANCE;

	private static String GET_PROBLEM_BY_ID = "select * from cws_problem";

	public ProblemDto getProblemById(Transaction transaction, int id) throws SQLException{

		ResultSet rs =null;
		PreparedStatement ps =null;
		try {
			transaction.begin();
			Connection conn = transaction.getResource(Connection.class);
			ps = conn.prepareStatement(GET_PROBLEM_BY_ID);
			rs = ps.executeQuery();
			while(rs.next()){
				return makeProblemDto(transaction, rs);
			}

			return new ProblemDto(-1, 0, new Date(System.currentTimeMillis()));

		} catch (SQLException se) {

			se.printStackTrace();

		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			transaction.preDestroy();
		}

		return new ProblemDto(-1, 0, new Date(System.currentTimeMillis()));


	}

	public List<ProblemDto> getAllProblems(Transaction transaction) throws SQLException{

		ResultSet rs =null;
		PreparedStatement ps =null;
		try {
			transaction.begin();
			Connection conn = transaction.getResource(Connection.class);
			ps = conn.prepareStatement(GET_PROBLEM_BY_ID);
			rs = ps.executeQuery();
			List<ProblemDto> problems = new ArrayList<ProblemDto>();
			while(rs.next()){
				problems.add(makeProblemDto(transaction, rs)) ;
			}

			return problems;

		} catch (SQLException se) {

			se.printStackTrace();

		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			transaction.preDestroy();
		}
		return new ArrayList<ProblemDto>();

	}

	private ProblemDto makeProblemDto(Transaction transaction, ResultSet rs) throws SQLException {
		int problem_id=rs.getInt(1);
		int use = rs.getInt(2);
		Date d = rs.getDate(3);
		return new ProblemDto(problem_id, use, d);
	}
}
